<?php

namespace app\controllers;

use Phalcon\Http\Request\File;
use Phalcon\Image;
use Phalcon\Mvc\Url;

class UploadController extends BaseController
{

    const TYPE_IMAGES = ['png', 'jpeg', 'gif', 'bmp', 'jpg'];

    const MAX_IMAGE_SIZE = 2048000;

    public function dispatchAction()
    {
        $action = $this->request->get('action');
        switch ($action) {
            case 'config' :
                return $this->config();
            break;
            case 'image' :
                return $this->image();
            break;
        }
        return [
            'error' => true,
            'message' => 'undefined request'
        ];
    }

    public function image()
    {
        if (!$this->request->hasFiles()) {
            return $this->response->setJsonContent([
                'status' => "FAILED",
                'message' => 'please select upload image'
            ]);
        }
        $files = $this->request->getUploadedFiles();
        if (count($files) > 1) {
            return $this->response->setJsonContent([
                'error' => true,
                'message' => 'only upload a file at a time'
            ]);
        }
        /**
         * @var  File $file
         */
        $file = current($files);
        if ($file->getKey() != 'file') {
            return $this->response->setJsonContent([
                'error' => true,
                'message' => 'key error'
            ]);
        }
        $size = $file->getSize();
        if ($size > self::MAX_IMAGE_SIZE) {
            return $this->response->setJsonContent([
                'error' => true,
                'message' => 'max size is 2m'
            ]);
        }
        $date = date('Y-m-d');
        $path = BASE_PATH . '/public/upload/image/' . $date;
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        $filename = uniqid() . '.' . $file->getExtension();
        if (!$file->moveTo($path . '/' . $filename)) {
            return $this->response->setJsonContent([
                'error' => true,
                'message' => 'save file error'
            ]);
        }
        return $this->response->setJsonContent([
            'state' => 'SUCCESS',
            'url' => '/upload/image/'. $date . '/' . $filename,
            'title' => $filename,
            'original' => $filename
        ]);
    }

    public function config()
    {
        return $this->response->setJsonContent([
            'imageActionName' => 'image',
            'imageFieldName' => 'file',
            'imageMaxSize' => 2048000,
            'imageAllowFiles' => ['.png', '.jpg', '.jpeg', '.gif', '.bmp'],
            'imageCompressEnable'=> true, /* 是否压缩图片,默认是true */
            'imageCompressBorder'=> 1600, /* 图片压缩最长边限制 */
            'imageInsertAlign'=> 'none', /* 插入的图片浮动方式 */
            'imageUrlPrefix'=> '', /* 图片访问路径前缀 */
            'imagePathFormat'=> '/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}',
        ]);
    }
}